package org.batatasframework.support.database.sql;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.batatasframework.support.database.LogicSymbol;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.database.sql.sort.SortFragment;
import org.batatasframework.support.database.sql.where.QueryFragment;
import org.batatasframework.support.database.sql.where.QueryFragmentAppender;

public class TableRuntimeBase extends TableInstance implements QueryFragmentAppender{

	/** 主表及其关联表的查询条件 */
	protected final List<QueryFragment> where = new ArrayList<>();
	
	protected final List<SortFragment> sorts = new ArrayList<>();
	
	public TableRuntimeBase(TableMetadata tableMetadata, String alias) {
		super(tableMetadata, alias);
	}

	public Collection<QueryFragment> getQueries(){
		return where;
	}

	public Collection<SortFragment> getSorts(){
		Collections.sort(sorts);
		return sorts;
	}
	
	public SortFragment orderBy(SortFragment fieldSortable) {
		sorts.add(fieldSortable);
		return fieldSortable;
	}
	
	public QueryFragment addQuery(QueryFragment queryFragment){
		where.add(queryFragment);
		return queryFragment;
	}
	

	public String getWhereClause(List<QueryParameter> queryParamenters) throws Exception {
		if(where.isEmpty()) return "";
		
		StringBuilder buf = new StringBuilder( where.size() * 10 );
		for(QueryFragment qf : where){
			qf.parse(LogicSymbol.AND, buf, queryParamenters);
		}
		if(buf.length()==0) return "";
		return buf.substring(LogicSymbol.AND.getValue().length());
	}

	public String getSortClause() throws Exception {
		if(sorts.isEmpty()) return "";
		
		StringBuilder buf = new StringBuilder( sorts.size() * 10 );
		for(SortFragment sort : sorts){
			sort.parse(buf.append(','));
		}
		return buf.substring(1);
	}

}
